<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useEquipmentStore, type Equipment } from '@/stores/equipment'
import { useRentalStore } from '@/stores/rental'
import { ElMessage } from 'element-plus'
import { generateOrderNo } from '@/utils/orderUtils'

const equipmentStore = useEquipmentStore()
const rentalStore = useRentalStore()

const searchKeyword = ref('')
const selectedEquipment = ref<Equipment | null>(null)
const rentalDialogVisible = ref(false)
const rentalForm = ref({
  rentalStartDate: '',
  rentalEndDate: '',
  notes: ''
})

const filteredEquipment = ref<Equipment[]>([])

onMounted(async () => {
  try {
    await equipmentStore.fetchEquipmentList()
    filteredEquipment.value = equipmentStore.equipmentList.filter(eq => eq.status === 'AVAILABLE')
  } catch (error) {
    ElMessage.error('加载设备列表失败')
  }
})

const searchEquipment = () => {
  if (!searchKeyword.value.trim()) {
    filteredEquipment.value = equipmentStore.equipmentList.filter(eq => eq.status === 'AVAILABLE')
  } else {
    filteredEquipment.value = equipmentStore.equipmentList.filter(eq => 
      eq.status === 'AVAILABLE' && 
      (eq.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
       eq.brand.toLowerCase().includes(searchKeyword.value.toLowerCase()))
    )
  }
}

const openRentalDialog = (equipment: Equipment) => {
  selectedEquipment.value = equipment
  rentalDialogVisible.value = true
  rentalForm.value = {
    rentalStartDate: '',
    rentalEndDate: '',
    notes: ''
  }
}

const submitRental = async () => {
  if (!selectedEquipment.value) return
  
  try {
    const startDate = new Date(rentalForm.value.rentalStartDate)
    const endDate = new Date(rentalForm.value.rentalEndDate)
    const days = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1
    
    const rental = {
      orderNo: generateOrderNo(),
      userId: 2,
      equipmentId: selectedEquipment.value.id,
      rentalStartDate: rentalForm.value.rentalStartDate,
      rentalEndDate: rentalForm.value.rentalEndDate,
      plannedReturnDate: rentalForm.value.rentalEndDate,
      dailyRentPrice: selectedEquipment.value.dailyRentPrice,
      totalAmount: selectedEquipment.value.dailyRentPrice * days,
      depositAmount: selectedEquipment.value.dailyRentPrice * 2,
      notes: rentalForm.value.notes
    }
    
    await rentalStore.createRental(rental)
    ElMessage.success('租赁订单创建成功')
    rentalDialogVisible.value = false
    await equipmentStore.fetchEquipmentList()
    filteredEquipment.value = equipmentStore.equipmentList.filter(eq => eq.status === 'AVAILABLE')
  } catch (error) {
    ElMessage.error('创建租赁订单失败')
  }
}

const getStatusColor = (status: string) => {
  switch (status) {
    case 'AVAILABLE': return 'success'
    case 'RENTED': return 'warning'
    case 'MAINTENANCE': return 'info'
    case 'DAMAGED': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'AVAILABLE': return '可用'
    case 'RENTED': return '已租'
    case 'MAINTENANCE': return '维护中'
    case 'DAMAGED': return '损坏'
    default: return '未知'
  }
}
</script>

<template>
  <div class="equipment-list">
    <div class="page-header">
      <h1>可租赁设备</h1>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索设备名称或品牌"
        style="width: 300px"
        @input="searchEquipment"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <div class="equipment-grid">
      <el-row :gutter="20">
        <el-col :span="6" v-for="equipment in filteredEquipment" :key="equipment.id">
          <el-card class="equipment-card" shadow="hover">
            <div class="equipment-image">
              <el-icon size="60"><Monitor /></el-icon>
            </div>
            <div class="equipment-info">
              <h3>{{ equipment.name }}</h3>
              <p class="brand">{{ equipment.brand }} · {{ equipment.model }}</p>
              <p class="description">{{ equipment.description }}</p>
              <div class="price">
                <span class="price-symbol">¥</span>
                <span class="price-value">{{ equipment.dailyRentPrice }}</span>
                <span class="price-unit">/天</span>
              </div>
              <div class="status-row">
                <el-tag :type="getStatusColor(equipment.status)">
                  {{ getStatusText(equipment.status) }}
                </el-tag>
              </div>
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  @click="openRentalDialog(equipment)"
                  :disabled="equipment.status !== 'AVAILABLE'"
                >
                  立即租赁
                </el-button>
                <el-button>查看详情</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-dialog v-model="rentalDialogVisible" title="创建租赁订单" width="500px">
      <div v-if="selectedEquipment">
        <div class="rental-equipment-info">
          <h4>{{ selectedEquipment.name }}</h4>
          <p>{{ selectedEquipment.brand }} {{ selectedEquipment.model }}</p>
          <p class="rental-price">日租金：¥{{ selectedEquipment.dailyRentPrice }}</p>
        </div>
        
        <el-form :model="rentalForm" label-width="100px">
          <el-form-item label="开始日期" required>
            <el-date-picker
              v-model="rentalForm.rentalStartDate"
              type="date"
              placeholder="选择开始日期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="结束日期" required>
            <el-date-picker
              v-model="rentalForm.rentalEndDate"
              type="date"
              placeholder="选择结束日期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="rentalForm.notes"
              type="textarea"
              placeholder="请输入备注信息"
              :rows="3"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rentalDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRental" :loading="rentalStore.loading">
            确认租赁
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.equipment-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.equipment-grid {
  margin-top: 20px;
}

.equipment-card {
  margin-bottom: 20px;
  transition: transform 0.2s;
}

.equipment-card:hover {
  transform: translateY(-2px);
}

.equipment-image {
  text-align: center;
  padding: 20px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  margin-bottom: 16px;
}

.equipment-image .el-icon {
  color: white;
}

.equipment-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.brand {
  color: #909399;
  margin: 0 0 8px 0;
  font-size: 14px;
}

.description {
  color: #606266;
  margin: 0 0 16px 0;
  font-size: 13px;
  line-height: 1.4;
}

.price {
  margin-bottom: 12px;
}

.price-symbol {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

.price-value {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.price-unit {
  color: #909399;
  font-size: 14px;
}

.status-row {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons .el-button {
  flex: 1;
}

.rental-equipment-info {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.rental-equipment-info h4 {
  margin: 0 0 8px 0;
  color: #303133;
}

.rental-equipment-info p {
  margin: 4px 0;
  color: #606266;
}

.rental-price {
  color: #f56c6c !important;
  font-weight: bold;
}
</style>